package com.adminapi.controller

import com.base.model.admin_api.Model_AdminAPI
import com.base.model.admin_api.Model_AdminAPI_Admin
import com.base.model.admin_api.Model_AdminAPI_Shiro
import com.base.service.IRPC_AdminAPI
import com.google.code.kaptcha.impl.DefaultKaptcha
import com.yfree.global.YController
import com.yfree.utils.YAESCrypt
import com.yfree.utils.YMD5Utils
import io.seata.spring.annotation.GlobalTransactional
import org.springframework.cloud.context.config.annotation.RefreshScope
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import java.io.ByteArrayOutputStream
import java.util.*
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@RefreshScope
@RestController
class Controller_AdminAPI(
    val defaultKaptcha: DefaultKaptcha
) : YController(), IRPC_AdminAPI {
    val cacheCodes = hashMapOf<String, String>()

    @GlobalTransactional
    override fun index() = yResult()

    @GlobalTransactional
    @RequestMapping("/getCode", method = [RequestMethod.GET])
    fun getCode(request: HttpServletRequest, response: HttpServletResponse) {
        val username = request.getParameter("username")
        if (username.isNullOrEmpty()) {
            response.outputStream.write("username为空".toByteArray())
            response.outputStream.flush()
            response.outputStream.close()
            return
        }
        val createText = defaultKaptcha.createText()
        cacheCodes[username] = createText
        val jpegOutputStream = ByteArrayOutputStream()
        ImageIO.write(defaultKaptcha.createImage(createText), "jpg", jpegOutputStream)
        response.setHeader("Cache-Control", "no-store")
        response.setHeader("Pragma", "no-cache")
        response.setDateHeader("Expires", 0)
        response.contentType = "image/jpeg"
        response.outputStream.write(jpegOutputStream.toByteArray())
        response.outputStream.flush()
        response.outputStream.close()
    }

    @GlobalTransactional
    override fun `interface`(jkid: String, jkparam: Any?): String {
        val params = yParams(jkparam, Map::class.java)
        return when (jkid) {
            "01A01" -> { // 后端模板登录
                val param_username = params["username"].toString()
                val param_password = params["password"].toString()
                if (param_username == "YFree" && YMD5Utils.getMD5(param_password) == YMD5Utils.getMD5("YFree"))
                    yResult(
                        result = listOf(
                            Model_AdminAPI(listOf("张三", "李四"), 1)
                        )
                    )
                else yResult(code = -1, message = "用户名或密码错误")
            }

            "01A02" -> { // 后端模板登录_shiro
                val param_username = params["username"].toString()
                when (param_username) {
                    "YFree1" -> yResult(
                        result = listOf(
                            Model_AdminAPI_Shiro(param_username, YMD5Utils.getMD5("YFree1"), "YFree1", arrayOf("YFree1"))
                        )
                    )

                    "YFree2" -> yResult(
                        result = listOf(
                            Model_AdminAPI_Shiro(param_username, YMD5Utils.getMD5("YFree2"), "YFree2", arrayOf("YFree2"))
                        )
                    )

                    else -> yResult(code = -1, message = "用户名不存在")
                }
            }

            "02A01" -> { // 前后分离客户端登录
                val param_username = params["username"].toString()
                val param_password = YAESCrypt.decrypt(params["password"].toString(), "000000000000")
                val param_code = params["code"].toString()
                if (param_username != "YFree" || param_password != "YFree")
                    return yResult(code = -1, message = "用户名或密码错误")
                if (cacheCodes[param_username] != param_code)
                    return yResult(code = -2, message = "验证码错误")
                val model_AdminAPI_Admin = Model_AdminAPI_Admin()
                model_AdminAPI_Admin.uid = "1"
                model_AdminAPI_Admin.nickname = "YFree"
                model_AdminAPI_Admin.login_time = Date().time.toString()
                model_AdminAPI_Admin.sign_token = "sign_token"
                model_AdminAPI_Admin.sign_password = "sign_password"
                model_AdminAPI_Admin.menuModels = gson.fromJson<List<Map<String, Any>>>(
                    """[
                        {
                          "title": "一级分类",
                          "route": "",
                          "subItems": [
                            {
                              "title": "二级分类",
                              "route": "",
                              "subItems": [
                                {
                                  "title": "三级分类",
                                  "route": "",
                                  "subItems": [
                                    {"title": "组件", "route": "page_view", "subItems": []},
                                    {"title": "Tab标签", "route": "page_tab", "subItems": []}
                                  ]
                                }
                              ]
                            }
                          ]
                        }
                      ]""", List::class.java
                )
                yResult(result = listOf(model_AdminAPI_Admin))
            }

            else -> yResult(code = 404, message = "jkid不存在")
        }
    }
}
